package com.wk.warehouse.service.impl;

import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wk.warehouse.entity.Auth;
import com.wk.warehouse.entity.Role;
import com.wk.warehouse.mapper.AuthMapper;
import com.wk.warehouse.mapper.RoleMapper;
import com.wk.warehouse.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class RoleServiceImp implements RoleService {
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private AuthMapper authMapper;

	/**
	 * 查询角色
	 */
	@Override
	public List<Role> findRoleList() {
		return roleMapper.findRoleList();
	}

	/**
	 * 查询角色
	 */
	@Override
	public List<Role> selectRoles(HashMap<String, Object> hashmap) {
		return roleMapper.selectRoles(hashmap);
	}

	/**
	 * 查询总条数
	 */
	@Override
	public int roleCount(HashMap<String, Object> hashmap) {
		return roleMapper.roleCount(hashmap);
	}

	/**
	 * 根据角色code查找
	 */
	public int findByCode(String roleCode) {
		return roleMapper.findByCode(roleCode);
	};

	/**
	 * 添加角色
	 */
	@Override
	public int insertRole(Role role) {
		return roleMapper.insertRole(role);
	}

	/**
	 * 修改角色状态
	 */
	@Override
	public int updateState(Role role) {
		return roleMapper.updateState(role);
	}

	/**
	 * 修改角色信息
	 */
	@Override
	public int updateRole(Role role) {
		return roleMapper.updateRole(role);
	}

	/**
	 * 查询未禁用角色
	 */
	@Override
	public List<Role> queryRole() {
		return roleMapper.queryRole();
	}

	/**
	 * 查询用户已有的角色
	 */
	@Override
	public List<Role> userRoleList(Integer userId) {
		return roleMapper.userRoleList(userId);
	}
	/**
	 * 根据角色名查角色id
	 */
	@Override
	public int findRoleIdByName(String roleName) {
		return roleMapper.findRoleIdByName(roleName);
	}

	/**
	 * 授予权限
	 */
	@Override
	public int grantAuth(int roleId, List<Integer> authIds) {
		int updateRows = 0;
		roleMapper.deleteAuthById(roleId); // 删除角色的所有权限
		HashMap<String, Object> map = new HashMap<>();
		map.put("roleId", roleId);
		for (int authId : authIds) {
			map.put("authId", authId);
			roleMapper.insertRoleAuth(map); // 给角色添加权限
			updateRows++;
		}
		return updateRows;
	}
	/**
	 * 根据角色id查询角色权限
	 */
	@Override
	public List<Integer> roleAuth(int roleId) {
		return roleMapper.roleAuth(roleId);
	}

	/**
	 * 删除角色
	 */
	@Override
	public int deleteRole(int roleId) {
		return roleMapper.deleteRole(roleId);
	}

}
